<template>
  <view :style="objColor" class="pages-wrap">
    <view class="sitePage">
      <!-- 站点信息 -->
      <view class="siteDetail">
        <view class="title">{{ siteItemData.name }}</view>
        <view class="info">
          <view class="address">
            <image
              class="img"
              src="https://oos-cn.ctyunapi.cn/front-end/static/homeSub/images/add.png"
            ></image>
            {{ siteItemData.street }}
          </view>
          <view
            class="item"
            @tap.stop.prevent="goAddress"
            :data-latitude="siteItemData.latitude"
            :data-longitude="siteItemData.longitude"
            :data-name="siteItemData.name"
            :data-street="siteItemData.street"
            v-if="siteItemData.distance != null"
          >
            {{ siteItemData.distance }}km
            <image
              class="img"
              :src="
                (otherIconListSync[0] && otherIconListSync[0].icon) ||
                'https://oos-cn.ctyunapi.cn/front-end/static/static/Navigation.png'
              "
              mode="aspectFill"
            ></image>
          </view>
          <view class="item" v-if="siteItemData.distance == null"
            >未授权定位</view
          >
        </view>
        <view class="info2">
          <view class="info-title">收费标准</view>
          <view class="text1" @click="showTip">
            查看详情
						<uni-icons class="txtIcon" type="right" size="18" :color="objColor2.textColor"></uni-icons>
          </view>
        </view>
        <view class="info2">
          <view class="info-title">充电桩号</view>
          <view class="text2">{{ pileNo }}</view>
        </view>
        <view class="info2">
          <view class="info-title">可用金额</view>
          <view class="recharge-btn-box">
            <template v-if="memberInfo.tokenMemberType != 0">
              <!-- 子成员 -->
              <text v-if="memberInfo.deductMode == 'LeaguerAccount'">
                <text style="color: #fc724c;">{{ memberInfo.carAccountBalance }}</text>元
              </text>
              <!-- 车队 -->
              <text v-if="memberInfo.deductMode == 'TeamAccount'">
                <text style="color: #fc724c;">****</text>
              </text>
             
            </template>
            <template v-else>
              <view class="btn" @click="rechargeVisible">充值</view>
              <text>¥{{memberInfo.memberType ? memberInfo.carAccountBalance : memberInfo.accountBalance }}</text>
            </template>
           
          </view>
        </view>

        <!-- 开启即充即付 && 是宣城项目 -->
        <!-- <view v-if="payType === '-1' && isSellerXc()" class="info2">
          <view class="info-title">即充即付</view>
          <view class="recharge-btn-box">
            <input class="t_input" type="digit" :value="customPrice" @input="getCustomPriceCwjt" placeholder="请输入预付金额" />
            <text>元</text>
          </view>
        </view> -->
      </view>

      <view v-if="payType === '-1'" class="detail-box">
        <view class="top-info amount-top">
          <text class="left">即充即付</text>
          <!-- 自定义时才手动填充值金额 -->
          <view v-if="amountIndex == 4" class="right input-right">
            <input class="amount-input" type="digit" :value="customPrice" @input="getCustomPriceCwjt" placeholder="请输入预付金额" />
            <text>元</text>
          </view>
        </view>
        <view class="tips-text">充满自动停止，多余的金额会自动退还</view>
        <view class="bottom-info" v-if="amountList.length">
          <view class="amount-box">
            <view :class="{'amount-item': true, 'amount-active': amountIndex == index + 1}" v-for="(item, index) in amountList" :key="index" @click="onAmountItem(item, index + 1)">{{item.label}}</view>
          </view>
        </view>
      </view>

      <view class="detail-box">
        <view class="top-info">
          <text class="left">充电枪号</text>
          <text class="right">选充电枪口: {{ checkGunStr }}</text>
        </view>
        <view class="bottom-info">
          <!-- <swiper
            class="activ-in"
            :indicator-dots="true"
            :autoplay="false"
            :interval="3000"
            :duration="500"
            indicator-col="#FEA48F"
            indicator-active-color="#FFFFFF"
            next-margin="-1rpx"
          >
            <block v-for="(item, index) in gunListGroup" :key="index">
              <swiper-item class="swiper-item-box"> -->
                <view
                  v-for="(cItem, cIndex) in gunList"
                  class="gun-item"
                  :class="{
                    'active-action': activeId === cItem.gunno,
                    'disable-action': ![1, 2, 4].includes(cItem.gunState),
                  }"
                  @click="selectGun(cItem)"
                  :key="cItem.gunid"
                >
                  <!-- 小蓝从1、平台从0开始 -->
                  <text class="num">{{
                    `端口${
                    cItem.gunno > 9 ? Number(cItem.gunno)  : "0" + (Number(cItem.gunno) )
                  }`
                  }}</text>
                  <text class="status">{{
                    cItem.gunState | filterStatus
                  }}</text>
                  <image
                    class="select"
                    :src="
                      (mixRechargeIconList[1] && mixRechargeIconList[1].icon) ||
                      'https://oos-cn.ctyunapi.cn/front-end/static/static/checkbox_sel2.png'
                    "
                    v-show="activeId === cItem.gunno"
                  ></image>
                </view>
              <!-- </swiper-item>
            </block>
          </swiper> -->
        </view>
      </view>
      
      <view class="detail-box" v-show="!customPrice">
        <view class="top-info">
          <text class="left">充电时长</text>
          <text class="right">时长:{{ checkTimeStr }}</text>
        </view>
        <view class="bottom-info">
          <view class="time-item-box">
            <view
              class="time-item"
              :class="{ 'time-active': activeTime === item.value }"
              v-for="(item, index) in timeList"
              :key="item.value"
              @click="selectTime(item)"
            >
              {{ item.label }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view style="height: 10rpx"></view>
    <view class="fixed-bottom-btn-box">
      <!-- 文本提示-暂时注释 -->
      <!-- <view class="rechargeRemind" v-if="recharge.value && !customPrice">{{ recharge.text }}</view> -->
      <template v-if="isLogin ">
        <view class="charge-btn fot_btn2" v-if="isStart" >启动充电</view>
        <view class="charge-btn" v-else @click="whetherChargeFd">启动充电</view>
      </template>
      <view class="charge-btn" v-else @click="whetherCharge3"
        >登录启动充电</view
      >
    </view>

    <!-- 收费须知 -->
    <u-popup :show="showPop" mode="center">
      <view class="tip-container">
        <view class="title">收费须知</view>
        <view class="info-box">
          <view class="sub-title">收费标准</view>
          <view class="rule-info">
            <div v-for="(item, index) in stationPhraseRules" :key="item.id">{{
              item.remark
            }}</div>
          </view>
        </view>
        <view class="info-box">
          <view class="sub-title">收费规则：</view>
          <view class="content">
            <view>1.每{{ longTime }}分钟作为一个计费周期，未满{{ longTime }}分钟的按一个周期计费。</view>
            <view>2.为确保充电安全，设置了充满自停功能，单次最长充电时长不超过8小时。</view>
            <view>3.功率以充电桩自检结果为准</view>
          </view>
        </view>
        <view class="btn" @click="closePop">我知晓并且同意</view>
      </view>
    </u-popup>
  </view>
</template>
<script>
import { getWechatMiniProgramTemplateId } from "@/api/wechatMiniProgramTemplateId";
var https_1 = require("./../../../api/https.js");
var util = require("@/utils/util.js");
var debounce = new util.Debounce();
let waitingTimes = "";

export default {
  data() {
    return {
      memberInfo: { accountBalance: "0.00" },
      stationId: "",
      otherIconListSync: [],
      recharge: {
        text: '余额不足请充值',
        value: false
      },
      siteItemData: {
        name: "",
        stationLabel: [],
        detailsImages: [],
        timeList: [],
        street: "",
        latitude: "",
        longitude: "",
        distance: "",
        notice: "",
        noticeStatus: "",

        gunPriceInfo: {
          superItem: {
            freeGunCount: "",
            gunCount: "",
            currentStartTime: "",
            currentEndTime: "",
            discount: "",
            currentPrice: "",
            currentPowerPrice: "",
            currentServicePrice: "",
          },

          fastItem: {
            freeGunCount: "",
            gunCount: "",
            currentStartTime: "",
            currentEndTime: "",
            discount: "",
            currentPrice: "",
            currentPowerPrice: "",
            currentServicePrice: "",
          },

          slowItem: {
            freeGunCount: "",
            gunCount: "",
            currentStartTime: "",
            currentEndTime: "",
            discount: "",
            currentPrice: "",
            currentPowerPrice: "",
            currentServicePrice: "",
          },
        },

        hasCoupons: "",
        parkingFeeDesc: "",
        managerPhone: "",
        id: "",
        isCollection: false,
        business: false,
        serviceTime: false,
      },
      stationPhraseRules: [{ remark: "" }],
      gunList: [],
      gunListGroup: [],
      timeList: [
        { label: "充满自停", value: 0 },
      ],
      gunId: 0,
      activeId: 0,
      pileNo: "",
      gunNo: "",
      checkGunStr: "无",
      activeTime: 0,
      checkTimeStr: "充满自停",
      showPop: false,
      isLogin: false,
      wxTemplateIds1: [],
      hulianinterfaceId: null,
      showBalance: false,
      longTime: 30,

      customPrice: '', // 即充即付金额
      payType: '', // 支付类型 -1: 充完即退
      orderNo: '',
      getRechargeResultNum: 1,
      rechargeLoading: false,
      rechargeError: false,
      Interval: null,
      isStart: false, // 是否启动充电
      amountList: [
        { label: '￥1.00', value: 1 },
        { label: '￥2.00', value: 2 },
        { label: '￥3.00', value: 3 },
        { label: '自定义', value: 0 },
      ],
      amountIndex: 0, // 对应amountList索引，不选就为null
    };
  },
  onLoad(options) {
    this.stationId = options.stationId;
    this.pileNo = options.pileNo;

    // 二维码携带枪号时,默认枪口选中
    if(options.gunNo && options.gunNo !== 'undefined'){
      this.gunNo = options.gunNo
      this.activeId = options.gunNo
      this.checkGunStr = `端口${this.gunNo > 9 ? Number(this.gunNo) : "0" + (Number(this.gunNo)) }`
    }
    
    //  默认：选择第一项
    // const count = 0
    // this.onAmountItem(this.amountList[count], count + 1) // 默认选择1元
  },
  async onShow() {
    this.otherIconListSync = uni.getStorageSync("otherIconList");

    if (this.pileNo) {
      await this.getPileDTOByNo();
      await this.getStationDetail(this.stationId);
      await this.getStationGunPriceDetail(this.gunId);
    } else if (this.stationId) {
      await this.getStationDetail(this.stationId);
      await this.getStationGunPriceDetail(this.gunId);
      this.getPileDTOByNo();
    }
    if (uni.getStorageSync("token")) {
      this.isLogin = true;
      this.getMemberInfo();
    } else {
      this.isLogin = false;
    }
    waitingTimes = setInterval(() => {
      Promise.all([this.getPileDTOByNo()]);
    }, 5000);
  },
  onHide() {
    clearInterval(waitingTimes);
  },
  onUnload() {
    clearInterval(waitingTimes);
  },
  methods: {
    // 检测已开通的支付方式
    getQuery(disposablePayMode) {
      https_1.queryList({
        disposablePayMode
      }).then((res)=> {
        const { code, data } = res
        if (code === 0) {
          data.forEach(item => {
            if (item.accountName === '充完即退') {
              this.payType = '-1'
            }
          })
        }
      })
    },

    // 即充即付-输入时触发
    getCustomPriceCwjt (e) {
      this.customPrice=e.detail.value
    },

    //获取站点详情
    async getStationDetail(stationId) {
      let getStationDetailById = uni.getStorageSync("token")
        ? https_1.getStationDetailByIdNew
        : https_1.getStationDetailByIdNotAuth;
      const res = await getStationDetailById({
        stationId: stationId,
        latitude: uni.getStorageSync("latitude"),
        longitude: uni.getStorageSync("longitude"),
      });
      if (res.code == 0) {
        this.siteItemData = res.data;
        const { gunPriceInfo } = res.data;
        this.gunId =
          gunPriceInfo?.slowItem?.gunId ||
          gunPriceInfo?.fastItem?.gunId ||
          gunPriceInfo?.superItem?.gunId ||
          gunPriceInfo?.lowestPriceItem?.gunId ||
          "";
      }
    },
    // 获取终端详情
    async getPileDTOByNo() {
      await https_1
        .getPileDTOByNo({
          pileNo: this.pileNo,
          sellerId: getApp().globalData.sellerId,
        })
        .then((res) => {
          if (res.code == 0) {
            this.hulianinterfaceId = res.data.hulianinterfaceId
            this.stationId = res.data?.stationId || "";
            this.gunList = res.data?.gunDTOList || [];
            this.gunList.sort((a,b)=> (a.gunno - b.gunno))
            if (this.gunList.length > 0) {
              // 默认取第一个枪ID
              this.gunId = this.gunList[0].gunid
            }

            // const newArray = [];
            // for (let i = 0; i < this.gunList.length; i += 8) {
            //   newArray.push(this.gunList.slice(i, i + 8));
            // }
            // this.gunListGroup = newArray;
          } else {
            uni.showToast({
              title: res.msg,
              icon: "error",
              duration: 2000,
            });
          }
        });
    },
    //获取站点详情(查询枪最低价格信息)
    async getStationGunPriceDetail(gunId) {
      var that = this;
      let getApiUrl = uni.getStorageSync("token")
        ? https_1.getStationGunDetails
        : https_1.getStationGunDetailsNotAuth;
      await getApiUrl(gunId)
        .then((res) => {
          if (res.code == 0) {
            if(!this.pileNo){
              this.pileNo = res.data?.pileNum || "";
            }
            
            this.stationPhraseRules = res.data?.stationPhraseRules || [
              { remark: "" },
            ];

            // protocolType
            // 4统一计费
            // 1分时计费(时段服务费)
            // 2分时计费(自定义服务费)         
            // 5按功率计费
            // 6按时间计费
            let protocolType = res.data?.stationRuleDTO?.protocolType
            if(protocolType==5){
              this.timeList = [
                { label: "充满自停", value: 0 },
                { label: "3小时", value: 3 * 60 },
                { label: "4小时", value: 4 * 60 },
                { label: "5小时", value: 5 * 60 },
                { label: "6小时", value: 6 * 60 },
                { label: "7小时", value: 7 * 60 },
                { label: "8小时", value: 8 * 60 },
              ]
            }else if(protocolType == 6){
              this.timeList = this.stationPhraseRules.map(item=>{
                return {
                  label:`${item.time}分钟`,
                  value:item.time
                }
              })
              this.timeList.unshift({ label: "充满自停", value: 0 })
            }

            this.longTime = res.data?.stationRuleDTO?.maxMoney || 30
            // this.showTip();
          }
        })
        .catch((err) => {
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000,
          });
        });
    },
    getMemberInfo() {
      https_1.getMemberInfo().then((res) => {
        var data = res.data;

        // #ifndef APP-PLUS
        // app 端暂不开放即使充即退模块
        if (data.memberType == 0) {
          this.getQuery(true)
        } else {
          this.getQuery()
        }
        // #endif

        if (data.accountBalance) {
          // 余额 = 余额-冻结金额-奖励金金额
          data.accountBalance = (
            (data.accountBalance - data.frozenAmount - data.jlAccountBalance) /
            100
          ).toFixed(2);

          if (data.accountBalance <= 0) {
            data.accountBalance = "0.00";
          }
        } else {
          data.accountBalance = "0.00";
        }

        if (data.carAccountBalance) {
          data.carAccountBalance = (data.carAccountBalance / 100).toFixed(2);
        } else {
          data.carAccountBalance = "0.00";
        }
        if (uni.getStorageSync("memberType").toString()) {
          data.memberType = uni.getStorageSync("memberType");
        } else {
          uni.setStorageSync("memberType", data.memberType);
        }

        this.memberInfo = data;
        if(data.accountBalance < '1') {
          // this.showBalance = true
          this.recharge = {
            text: '账户金额小于1元无法启动充电',
            value: true
          }
        }
      });
    },
    // 导航
    goAddress: function (e) {
      // console.log("导航",e)
      var latitude = parseFloat(e.currentTarget.dataset.latitude);
      var longitude = parseFloat(e.currentTarget.dataset.longitude);
      var name = e.currentTarget.dataset.name;
      var street = e.currentTarget.dataset.street;
      uni.openLocation({
        latitude: latitude,
        longitude: longitude,
        name: name,
        address: street,
      });
    },
    rechargeVisible() {
      uni.navigateTo({
        url: "/mine/pages/recharge/recharge?goBack=true",
      });
    },
    // 选择充电枪号
    selectGun(record) {
      if (![1, 2, 4].includes(record.gunState)) return;
      this.activeId = record.gunno;
      this.checkGunStr = `端口${
        record.gunno > 9 ? Number(record.gunno)  : "0" + (Number(record.gunno) )
      }`;
      this.gunNo = record.gunno;
      this.getStationGunPriceDetail(record.gunid)
    },
    selectTime(record) {
      this.activeTime = record.value;
      this.checkTimeStr = record.label;
    },
    showTip() {
      this.showPop = true;
    },
    closePop() {
      this.showPop = false;
    },
    // 启动充电防抖
    whetherChargeFd() {
      // 有值代表 即充即付
      if (this.customPrice!=0 || this.currentPrice) {
        console.log('即充即付 启动')
        debounce.use(() => {
          this.disposableStartCharge();
        }, 2000)();
      } else {
        console.log('余额支付')
        debounce.use(() => {
          this.whetherCharge();
        }, 2000)();
      }
    },

    // 启动充电-充完即退-微信支付前校验
    disposableStartCharge() {
      // 2024、8.15 谢芳要求2轮前端不判断最低启动金额
      // if (!this.customPrice || this.customPrice < 0.1) {
      //   uni.showModal({
      //     title: "信息提示",
      //     content: "即充即付金额小于0.1元无法启动充电",
      //     confirmColor: this.objColor2.textColor,
      //     success: (r) => {},
      //   });
      //   return
      // }

      if (this.isStart) return // 启动中, 不可重复点击

      uni.showLoading({
        title: '启动中',
        mask: true
      })

      this.isStart = true
      const str = {
        pileNo: this.pileNo,
        gunNo: this.gunNo,
        chargeMode: 0, // app充电模式(1自动模式,2金额模式,3时间模式,4电量模式)
        valtageType: 0, //辅助电源参数
        payMode: 1, //支付方式    
        preChargeAmount: Number(this.customPrice != '' ? this.customPrice : 0) //预冲金额
      };
      console.log('启动充电-充完即退-微信支付前校验:', str)
      https_1.disposableStartCharge(str).then((res)=> {
        if (res.code == 0) {
          this.disposableUnifiedOrders()
        }else{
          this.isStart = false
          uni.hideLoading()
          if (!this.gunNo || !this.pileNo) {
            uni.showModal({
              title: "消息提示",
              content: "请选择充电枪",
              confirmColor: this.objColor2.textColor,
              success: (r) => {},
            });
            return;
          }else{
            uni.showModal({
              title: '信息提示',
              content: res.msg || '启动异常，请退出重试',
              showCancel: false,
              success: (r) => {},
            });
          }
        }
      })
    },

    //启动充电-充完即退-微信预下单
    disposableUnifiedOrders () {
      console.log('启动充电-充完即退-微信预下单==>', this.siteItemData)
      uni.showLoading({
        title: '提交中...',
        mask: true
      });
     
      
      let openId = uni.getStorageSync('openId')
      console.log('--openId--', openId);
	  let reqForm = {
		  openId: openId ? openId : 'openid123456789',
		  gunId:this.siteItemData.gunId,
		  totalFee: this.customPrice*100,
		  tradeType: 'JSAPI', // 交易类型：JSAPI -JSAPI支付 NATIVE -Native支付 APP -APP支付
		  stationId: this.stationId,
	  }
	  // #ifdef MP-WEIXIN
	  reqForm.tradeType = 'JSAPI'
	  // #endif
	  
	  // #ifdef APP-PLUS
	  reqForm.tradeType = 'APP'
	  // #endif
	  
	  // #ifdef H5
	  reqForm.tradeType = 'TENPAY'
	  // #endif
	  
	  // #ifdef MP-ALIPAY
	  reqForm.payType = 2
	  // #endif
      https_1.disposableUnifiedOrders(reqForm).then((res) => {
        if (res.code == 0) {
          // 即充即退支付
          this.orderNo=res.data.orderNo
          console.log('<<<<<<<即充即退支付>>>>>>>>>', this.orderNo);
          this.goDisposablePay(res);
        }else{
          this.isStart = false
          uni.hideLoading();
          uni.showModal({
            title: '消息提示',
            content: res.msg || '服务异常',
            showCancel: false
          });
        }
      }).catch(err => {
        this.isStart = false
        uni.hideLoading();
        uni.showModal({
          title: '充值失败',
          content: err.msg || '服务异常',
          showCancel: false
        });
      })
    },

    //调起支付
    goDisposablePay: function (res) {
      var that = this;
      //#ifdef APP-PLUS
      var orderInfo = JSON.stringify({
        "appid": res.data.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
        "noncestr": res.data.noncestr, // 随机字符串
        "package": res.data.package, // 固定值
        "partnerid": res.data.partnerid, // 微信支付商户号
        "prepayid": res.data.prepayid, // 统一下单订单号
        "timestamp": res.data.timestamp, // 时间戳（单位：秒）
        "sign": res.data.sign // 签名，这里用的 MD5/RSA 签名
      })
      uni.requestPayment({
        provider: 'wxpay',
        orderInfo, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
        success: function (res) {
          console.log(res)
          that.getRechargeResult();
        },
        fail: function (err) {
          console.log(err)
          that.cancelCharge()
        }
      });
      //#endif
      
      // #ifdef MP-WEIXIN
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: res.data.signType,
        paySign: res.data.sign,
        success: function (res) {
          console.log('>>>requestPayment-success>>>',res)
          that.getRechargeResult();
        },
        fail: function (err) {
          console.log('调起支付-fail:',err)
          that.cancelCharge()
        }
      });
      // #endif
    },

    //查询充值结果
    getRechargeResult: function() {
      var that = this;
      this.rechargeLoading = true
      uni.showLoading({title:'充值中..',mask:true})

      // 旧轮询查询-每3秒1次，网络过慢会有问题
      // this.disposableOrderResultQuery();
      // this.Interval = setInterval(function() {
      //   if (that.getRechargeResultNum > 10) {
      //     uni.hideLoading()
      //     clearInterval(that.Interval);
      //     that.disposableCancelRecharge();
      //   } else {
      //     that.disposableOrderResultQuery();
      //   }
      // }, 3000);

      // 同步查询充值到账结果，3秒1次，超次数后就调用取消充值接口
      this.rollPolingPayStatus()
    },

    // 轮询支付结果-同步
    rollPolingPayStatus() {
      setTimeout(() => {
        // 3分钟都没查询成功，就调取消充值接口
        if (this.getRechargeResultNum > 60) {
          uni.hideLoading()
          this.disposableCancelRecharge();
        } else {
          this.disposableOrderResultQuery();
        }
      }, 3000)
    },

    //启动充电-充完即退-微信查询支付结果
    disposableOrderResultQuery: function() {
      var that = this;
      var num = this.getRechargeResultNum + 1;
      this.getRechargeResultNum = num
	  let reqForm = {
	  	orderNo: this.orderNo
	  }
	  // #ifdef MP-ALIPAY
	  reqForm.payType = 2
	  // #endif
      https_1
        .disposableOrderResultQuery(reqForm)
        .then(function(res) {
          if (res.code === 0) {
            that.enterDisposableStartCharge()
          } else {
            that.rollPolingPayStatus()
          }
        }).catch (err => {
          that.rollPolingPayStatus()
        })
    },

    //启动充电-充完即退-微信支付成功后鉴权
    enterDisposableStartCharge: function() {
      var that = this
      let customPrice = that.customPrice
      
      that.customPrice = ''
      uni.hideLoading()
      clearInterval(that.Interval)
      that.rechargeLoading = false
      that.getRechargeResultNum = 1
      that.isStart = false
      
      var str = {
        pileNo: this.pileNo,
        gunNo: this.gunNo,
        chargeMode: 0, // app充电模式(1自动模式,2金额模式,3时间模式,4电量模式)
        valtageType: 0, //辅助电源参数
        // carNum: this.plateNo, //车牌号
        payMode: 1, //支付方式    
        // qrCode: this.qrCode,
        preChargeAmount: Number(customPrice != '' ? customPrice : 0), //预冲金额
        orderNumber: this.orderNo,
        disposablePayMode: true,
        preChargePower: customPrice,
      };
      console.log(JSON.stringify(str), '8888888')
      uni.navigateTo({
        url: '/homeSub/pages/startCharging/startCharging?parameter=' + JSON.stringify(str) +
          '&stationId=' + this.stationId
      });
    },

    //启动充电-充完即退-微信取消充值 -- 支付后
    disposableCancelRecharge: function() {
      uni.showModal({
        title: '消息提示',
        content: '网络异常，如果产生多次扣费，请联系客服人员退款',
        showCancel: false
      });
      var that = this;
      https_1.disposableCancelRecharge({
        orderNo: this.orderNo
      }).then(function() {
        that.isStart = false
        that.rechargeLoading = false,
        that.rechargeError = true,
        that.getRechargeResultNum = 1
      });
    },

    //取消充值 -- 支付前
    cancelCharge: function() {
      uni.showLoading({
        title: '取消中...',
        mask: true
      });
		let reqForm = {
			openId: uni.getStorageSync('openid'),
			totalFee: this.customPrice * 100,
			tradeType: 'APP',
			orderNo: this.orderNo,
			cancelRecharge: 2
		}
		// #ifdef MP-ALIPAY
		reqForm.payType = 2
		// #endif
      https_1
        .disposableUnifiedOrders(reqForm)
        .then((res) => {
          uni.hideLoading()
          if (res.code == 0) {
            uni.showModal({
              title: '消息提示',
              content: '已取消充值',
              showCancel: false
            });
          }
          this.isStart = false
        }).catch((err) => {
          uni.hideLoading()
          uni.showModal({
            title: '取消充值',
            content: err.msg || '服务异常',
            showCancel: false
          });
        });
    },

    // 判断是否满足充电要求
    whetherCharge() {
      if (this.memberInfo.accountBalance <= 0) {
        uni.showModal({
          title: "消息提示",
          content: "当前余额不足！",
          confirmText: "去充值",
          confirmColor: this.objColor2.textColor,
          success: (r) => {
            if (r.confirm) {
              this.rechargeVisible();
            }
          },
        });
        return;
      }
      if (!this.gunNo || !this.pileNo) {
        uni.showModal({
          title: "消息提示",
          content: "请选择充电枪",
          confirmColor: this.objColor2.textColor,
          success: (r) => {},
        });
        return;
      }
      let that = this;

      if (this.isStart) return // 启动中, 不可重复点击

      uni.showLoading({
        title: '启动中',
        mask: true
      })
      this.isStart = true

      https_1.querMemberStatus().then(async (res) => {
        if (res.code == 0) {
          if (res.data.ifCharging) {
            that.isStart = false
            uni.hideLoading()
            // 在充电
            uni.showModal({
              title: "消息提示",
              content: "您当前正在充电",
              confirmText: "充电详情",
              confirmColor: that.objColor2.textColor,
              success: function (r) {
                if (r.confirm) {
                  // 查看充电详情
                  uni.navigateTo({
                    url: `/echartsPages/pages/power/power?busId=${res.data.billList[0].busId}&pileNo=${res.data.billList[0].pileNo}&gunNo=${res.data.billList[0].gunNo}`,
                  });
                }
              },
            });
          } else {
            that.requestSubscribeMessageDY(async () => {
              that.isStart = false
              uni.hideLoading()
              that.openCharge();
            });
          }
        } else {
          that.isStart = false
          uni.hideLoading()
          uni.showModal({
            title: "提示",
            content: res.msg ? res.msg : `启动失败`,
            showCancel: false,
            confirmText: "关闭",
            confirmColor: that.objColor2.textColor,
          });
        }
      });
    },
    //登录启动充电
    whetherCharge3() {
      getApp().globalData.CHECK_LOGIN_Model({}, "请先完成登录后再启动充电。");
    },
    openCharge() {
      // this.hulianinterfaceId没值 就是自营二轮、有值就是互联互通的二轮
      let limitValue = ''
      if(!this.hulianinterfaceId) {
        limitValue = this.activeTime === 0 ? this.memberInfo.accountBalance*60*60 : this.activeTime*60
      }else {
        limitValue = this.activeTime
      }
      
      const str = {
        pileNo: this.pileNo,
        gunNo: this.gunNo,
        chargeMode: this.activeTime === 0 ? 0 : 2, // 0-充满自停 2-时长
        limitValue:limitValue,
        // limitValue: 10, // 测试10分钟
        payMode: this.memberInfo.memberType ? 2 :1
      };
      uni.navigateTo({
        url:
          "/homeSub/pages/startCharging/startCharging?parameter=" +
          JSON.stringify(str),
      });
    },
    requestSubscribeMessageDY(fn) {
      let that = this;
      getWechatMiniProgramTemplateId({
        sellerId: getApp().globalData.sellerId,
        titleName: "结束充电提醒",
      }).then((res) => {
        this.wxTemplateIds1 = [res.data];
        console.log(res, "获取id");
        // #ifdef MP-WEIXIN
        if (!that.wxTemplateIds1.length) {
          fn();
          return;
        }
        wx.requestSubscribeMessage({
          tmplIds: that.wxTemplateIds1 || [],
          fail(err) {
            console.log(err, "eeeeeeeeeeeeeee2121212");
          },
          complete() {
            console.log("订阅消息回调2121212");
            fn();
          },
        });
        // #endif

        // #ifndef MP-WEIXIN
        fn();
        // #endif
      });
    },

    // 即充即付-选择
    onAmountItem(item, index) {
      this.amountIndex = index
      this.customPrice = item.value || ''
    }
  },
  filters: {
    filterStatus(val) {
      const statusEnum = {
        1: "空闲",
        2: "充电准备",
        3: "充电中",
        4: "充电完成",
        5: "离线",
        6: "充电锁定",
        7: "故障",
        8: "预约",
        9: "禁用",
        255: "默认",
      };
      if (val) {
        return statusEnum[val];
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import "../../../commin/commin.less";
page {
  background-color: #f5f7fa;
  padding-bottom: 100rpx;
}
.rechargeRemind {
  position: absolute;
  // top: -90rpx;
  top: -75rpx;
  right: 70rpx;
  background: linear-gradient(105deg, #F7B068, #F7A14A);
  box-shadow: 4rpx 7rpx 20rpx 0rpx rgba(166, 171, 179, 0.24);
  border-radius: 16rpx;
  font-size: 24rpx;
  font-family: PingFang SC;
  font-weight: 400;
  color: #FEFEFE;
  padding: 20rpx;
}
.sitePage {
  .margins(16rpx, 24rpx, 150rpx, 24rpx);
  background: linear-gradient(0deg, #ffffff, #f4f6f8);
  .borders(2rpx, @white-color);
  box-shadow: 4px 7px 20px 0px rgba(166, 171, 179, 0.24);
  .borderradius(16rpx, 16rpx, 16rpx, 16rpx);
  .kuan(654rpx);
  .paddings(24rpx, 24rpx, 24rpx, 24rpx);
}
.detail-box {
  margin-top: 80rpx;
  .top-info {
    display: flex;
    justify-content: space-between;
    font-size: 34rpx;
    font-family: PingFang SC;
    font-weight: bold;
    color: #1a1a1a;
    .right {
      color: #5bb054;
    }
  }
  .bottom-info {
    margin-top: 20rpx;
    // .swiper-item-box {
      display: flex;
      flex-wrap: wrap;
    //   // justify-content: center;
      gap: 10rpx 10rpx;
      .gun-item {
        width: 154rpx;
        height: 132rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: rgba(207, 231, 252, 1);
        position: relative;

        .num {
          color: var(--textColor);
          font-size: 24rpx;
          font-weight: bold;
        }
        .status {
          color: var(--textColor);
          font-size: 20rpx;
        }
      }
      .active-action {
        background: rgba(109, 177, 46, 0.08);
        box-shadow: 2rpx 3rpx 14rpx 0px rgba(166, 171, 179, 0.14);
      }
      .disable-action {
        background: rgb(215, 215, 215);

        .num,
        .status {
          color: #ffffff !important;
        }
      }
      .select {
        width: 56rpx;
        height: 56rpx;
        position: absolute;
        bottom: 0;
        right: 0;
        z-index: 9;
      }
    // }

    .time-item-box {
      display: flex;
      flex-wrap: wrap;
      // justify-content: center;
      gap: 10rpx;

      .time-item {
        &:first-child {
          width: 316rpx;
        }
        width: 152rpx;
        height: 48rpx;
        border-radius: 4rpx;
        text-align: center;
        line-height: 48rpx;
        border: 1rpx solid rgb(158, 157, 157);
        color: #6c6c6c;
        font-size: 28rpx;
      }
      .time-active {
        background-color: var(--textColor);
        border: 1rpx solid var(--textColor);
        color: #ffffff;
      }
    }
  }

  .amount-top {
    height: 70rpx;
    align-items: center;
    .input-right {
      display: flex;
      align-items: center;

      .amount-input {
        text-align: right;
        padding: 12rpx 24rpx;
      }

      text {
        color: #d45a54;
        font-size: 30rpx;
      }
    }
  }

  .tips-text {
    margin-top: 12rpx;
    margin-bottom: 24rpx;
    font-size: 28rpx;
    color: #909399;
  }
}
.siteDetail {
  // background: linear-gradient(0deg, #ffffff, #f4f6f8);
  // .borders(2rpx, @white-color);
  // box-shadow: 4px 7px 20px 0px rgba(166, 171, 179, 0.24);
  // .borderradius(16rpx, 16rpx, 16rpx, 16rpx);
  // .kuan(654rpx);
  // .paddings(24rpx, 24rpx, 24rpx, 24rpx);

  .info2 {
    margin-top: 40rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .info-title {
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: bold;
      color: #1a1a1a;
    }

    .text1 {
      font-size: 24rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #a6abb3;

      .txtImg {
        .kuangao(16rpx, 27rpx);
        margin-left: 17rpx;
      }
      .txtIcon {
        line-height: 1;
        margin-left: 4rpx;
      }
    }

    .text2 {
      font-size: 24rpx;
      font-family: PingFang SC;
      font-weight: 500;
    }
    .recharge-btn-box {
      display: flex;

      .btn {
        width: 130rpx;
        height: 40rpx;
        text-align: center;
        line-height: 40rpx;
        font-size: 20rpx;
        color: #ffffff;
        background: linear-gradient(to right, #ed7231, #f09d3a);
        margin-right: 20rpx;
        border-radius: 8rpx;
      }
      text {
        color: #d45a54;
        font-size: 30rpx;
      }
    }
  }

  .title {
    flex-wrap: wrap;
    display: flex;
    flex-direction: row;
    margin-bottom: 20rpx;
    font-weight: bold;
  }

  .tagList {
    display: flex;
    flex-wrap: wrap;

    .tag_item {
      background: rgba(96, 98, 102, 0.06);
      .borderradius(20rpx, 20rpx, 20rpx, 20rpx);
      .fontsize(24rpx);
      font-family: PingFang SC;
      font-weight: 400;
      color: @text-color4;
      padding: 9rpx 18rpx;
      .margins(12rpx, 10rpx, 12rpx, 10rpx);
    }

    .tag_item last {
      margin: 0;
    }
  }

  .siteImg {
    height: 120rpx;
    .margins(18rpx, 0, 31rpx, 0);

    .view_list {
      width: 100%;
      text-align: center;
      display: flex;
    }

    .mypic {
      width: 200rpx;
      height: 120rpx;
      margin-right: 12rpx;
      .borderradius(10rpx, 10rpx, 10rpx, 10rpx);
    }
  }

  .siteTime {
    display: flex;
    align-items: center;
    display: inline-block;
    .img {
      .kuangao(31rpx, 30rpx);
      margin-right: 9rpx;
    }

    .fontsize(24rpx);
    font-family: PingFang SC;
    font-weight: 500;
    color: @text-color3;
  }

  .info {
    display: flex;
    justify-content: space-between;
    margin-top: 27rpx;

    .address {
      .kuan(75%);
      .fontsize(24rpx);
      align-items: center;
      font-family: PingFang SC;
      font-weight: 500;
      color: @text-color3;

      .img {
        .kuangao(23rpx, 30rpx);
        margin-right: 12rpx;
        float: left;
      }
    }

    .item {
      .fontsize(24rpx);
      font-family: PingFang SC;
      font-weight: 500;
      color: @blue;

      .img {
        .kuangao(27rpx, 25rpx);
      }
    }
  }
  .notice {
    display: flex;
    background: #f5f7fa;
    .fontsize(24rpx);
    .paddings(30rpx, 24rpx, 16rpx, 24rpx);
    font-family: PingFang SC;
    font-weight: 500;
    color: @text-color4;
    line-height: 36rpx;
    margin-top: 31rpx;

    .img {
      .kuangao(29rpx, 20rpx);
    }

    .scrollIsf {
      margin-top: -8rpx;
      margin-left: 16rpx;
    }
  }
  .timeListCon {
    font-size: 24rpx;
    align-items: center;
    font-family: PingFang SC;
    font-weight: 500;
    color: #606266;
    margin-top: 25rpx;
    .timeListText {
      margin-left: 10rpx;
    }
    .img {
      .kuangao(31rpx, 30rpx);
      margin-right: 9rpx;
      vertical-align: middle;
    }
  }

  .showTime {
    padding: 9rpx 16rpx 8rpx 17rpx;
    display: inline-block;
    text-align: center;
    border: 1rpx solid @blue;
    border-radius: 8rpx;
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: @blue;
    margin-right: 8rpx;
  }
  .tagList {
    display: inline-block;
    line-height: 50rpx;
    .tagCon {
      display: inline;
    }
    .tagDivision {
      display: inline;
      position: relative;

      &::after {
        position: absolute;
        right: 0;
        top: 15rpx;
        content: "";
        height: 22rpx;
        width: 1px;
        background: #909399;
      }
    }
    .tag {
      font-size: 24rpx;
      font-family: PingFang SC;
      font-weight: 500;
      padding: 6rpx 16rpx;
      &.tag1 {
        border: 1px solid @blue;
        border-radius: 8rpx;
        color: @blue;
        margin: 0 4rpx;
      }
      &.tag2 {
        color: #909399;
        position: relative;

        // &::after {
        //     position: absolute;
        //     right: 0;
        //     top: 12rpx;
        //     content: '';
        //     height: 22rpx;
        //     width: 1px;
        //     background: #909399;
        // }
        // &:last-child {

        //     &::after {
        //         width: 0;
        //     }
        // }
      }
    }
  }
}
.fixed-bottom-btn-box {
  width: 698rpx;
  position: fixed;
  bottom: 0;
  background: linear-gradient(0deg, #ffffff, #f4f6f8);
  border: 2rpx solid rgba(255, 255, 255, 0.55);
  box-shadow: 0rpx -25rpx 67rpx 0rpx rgba(177, 182, 190, 0.2);
  .paddings(10rpx, 31rpx, 10rpx, 31rpx);

  .charge-btn {
    text-align: center;
    background: var(--btnColor);
    box-shadow: 0rpx 3rpx 6rpx 0rpx rgba(0, 110, 212, 0.3);
    border-radius: 44rpx 44rpx 44rpx 44rpx;
    font-size: 34rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #fff;
    line-height: 88rpx;
  }
  .fot_btn2 {
    background: #c0c4cc;
  }
}
.tip-container {
  width: 620rpx;
  padding: 40rpx;

  .title {
    text-align: center;
    font-size: 34rpx;
    font-weight: bold;
  }
  .info-box {
    margin-top: 40rpx;

    .sub-title {
      font-weight: bold;
    }

    .rule-info {
      margin-top: 20rpx;
      white-space: pre-wrap;
      color: #666666;
    }

    .content {
      margin-top: 20rpx;
      font-size: 30rpx;
      line-height: 60rpx;
      color: #aeaeae;
    }
  }

  .btn {
    text-align: center;
    background: var(--btnColor);
    box-shadow: 0rpx 3rpx 6rpx 0rpx rgba(0, 110, 212, 0.3);
    border-radius: 8rpx;
    height: 60rpx;
    line-height: 60rpx;
    color: #ffffff;
    margin-top: 40rpx;
  }
}


.amount-box {
display: flex;
flex-wrap: wrap;
gap: 10rpx 10rpx;
.amount-item {
  width: 154rpx;
  height: 110rpx;
  color: #666;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  border: 1rpx dashed #ccc;
  border-radius: 12rpx;
  line-height: 1;
  font-size: 30rpx;
}
.amount-active {
  background: var(--btnColor);
  color: #fff;
  border: 1rpx solid var(--btnColor);
}
}
</style>
